using DNSPodForNET;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DDnsPod
{
    public partial class DDnsPod : ServiceBase
    {
        String ip = String.Empty;
        String token = String.Empty;
        String domain = String.Empty;
        String record = String.Empty;
        String logFilePath = String.Empty;
        int recordId = 0;
        static System.Timers.Timer timer1 = new System.Timers.Timer();
        public DDnsPod()
        {
            InitializeComponent();
            token = ConfigurationManager.AppSettings["token"];
            domain = ConfigurationManager.AppSettings["domain"];
            record = ConfigurationManager.AppSettings["record"];
            logFilePath = ConfigurationManager.AppSettings["logFilePath"];
            timer1.AutoReset = true;
            timer1.Elapsed += Timer1_Tick;
        }

        protected override void OnStart(string[] args)
        {
            String DevelopMode = ConfigurationManager.AppSettings["DevelopMode"];//开发模式
            //如果是开发模式，在服务启动时让服务延迟25秒启动，以方便附加进程调试程序
            if (String.Equals(DevelopMode, "true", StringComparison.CurrentCultureIgnoreCase))
            {
                Thread.Sleep(25000);//调试服务时附加进程需要时间，为了防止服务进程还没有附加就已经退出了，所以先将服务延迟25秒
            }
            try
            {
                timer1.Interval = Int32.Parse(ConfigurationManager.AppSettings["Interval"]);
            }
            catch { 
                timer1.Interval = 10000;
            }
            finally
            {
                timer1.Enabled = true;
                timer1.Start();
            }
            base.OnStart(args);
        }

        protected override void OnStop()
        {
            timer1.Stop();
            base.OnStop();
        }



        protected override void OnPause()
        {
            timer1.Stop();
            base.OnPause();
        }

        protected override void OnContinue()
        {
            timer1.Start();
            base.OnContinue();
        }

        protected override void OnShutdown()
        {
            timer1.Stop();
            base.OnShutdown();
        }
        void OutMessage(string msg)
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(logFilePath, true))
            {
                sw.Write(msg);
            }
        }
        private void Timer1_Tick(object sender, EventArgs e)
        {
            String newIp = GetLocalIp();
            if (String.IsNullOrEmpty(ip) || (!String.IsNullOrWhiteSpace(newIp) && !String.Equals(ip,newIp, StringComparison.CurrentCultureIgnoreCase))) {
                if (String.IsNullOrEmpty(ip))
                {
                    OutMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "服务开启，"+ record + "." + domain + "的IP指向设置为[" + newIp + "]\r\n");
                }
                else
                {
                    OutMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "IP地址由[" + ip + "]变更为[" + newIp + "]\r\n");
                }
                DnsPodRecord dpr = new DnsPodRecord(token);
                if (recordId < 1) { 
                    var recordList = dpr.List(new { sub_domain = record, domain = domain });
                    if (recordList.records != null && recordList.records.Count > 0)
                    {
                        recordId = recordList.records[0].id;
                    }
                    else
                    {
                        recordId = dpr.Create(domain, record, newIp);
                    }
                }
                if (recordId > 0)
                {
                    dynamic result = dpr.DdnsNew(domain, recordId, newIp, record);
                    if (result.record.value!=null) {
                        ip = result.record.value;
                    }
                }
            }
        }

        /// <summary>
        /// 获取外网IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIp()
        {
            string result = String.Empty;
            try
            {
                result = HttpClient.HttpClient.GetHttpContent("http://2019.ip138.com/ic.asp", Encoding.GetEncoding("gb2312"));
                if (result.IndexOf("您的IP是：[") > 0) { result = result.Substring(result.IndexOf("您的IP是：[") + "您的IP是：[".Length); }
                if (result.IndexOf("[") > 0) { result = result.Substring(result.IndexOf("[") + "[".Length); }
                if (result.IndexOf("]") > 0) { result = result.Substring(0, result.IndexOf("]")); }
            }
            finally
            {
            }
            return result.Trim();
        }
    }
}
